package com.arunsawad.ilertu.activity;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.arunsawad.ilertu.R;
import com.arunsawad.ilertu.adapter.ServicesAdapter;
import com.arunsawad.ilertu.common.AsyncActivity;
import com.arunsawad.ilertu.common.Constants;
import com.arunsawad.ilertu.common.RequestTask;
import com.arunsawad.ilertu.common.RightDrawableOnTouchListener;
import com.arunsawad.ilertu.common.Validator;
import com.arunsawad.ilertu.dto.Service;

public class Services extends Activity implements AsyncActivity {
	SharedPreferences preferences;
	ListView listView;
	private List<Service> services = new ArrayList<Service>();
	private ServicesAdapter adapter;
	ProgressDialog bar;
	String categoryId = null;
	int page = 0;
	Button btnLoadMore;
	EditText txtSearch;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_services);
		preferences = getSharedPreferences(
				Constants.PREF_FILE, MODE_PRIVATE);
		Validator.Validate(this, preferences);
		
		txtSearch = (EditText) findViewById(R.id.services_txtSearch);
		final Drawable x = getResources().getDrawable(R.drawable.delete);

		txtSearch.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
				if (txtSearch.getText().toString().equals("")) {
					txtSearch.setCompoundDrawables(null, null, null, null);
				} else {
					x.setBounds(0, 0, x.getIntrinsicWidth(),
							x.getIntrinsicHeight());
					txtSearch.setCompoundDrawables(null, null, x, null);
				}
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
		});

		txtSearch.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					// Perform action on key press
					page = 0;
					services = new ArrayList<Service>();
					doSearch();
					return true;
				}
				return false;
			}
		});

		txtSearch.setOnTouchListener(new RightDrawableOnTouchListener(
				txtSearch, x) {
			public boolean onDrawableTouch(final MotionEvent event) {
				txtSearch.setText("");
				txtSearch.setCompoundDrawables(null, null, null, null);
				page = 0;
				services = new ArrayList<Service>();
				doSearch();
				return false;
			}
		});

		btnLoadMore = new Button(this);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			categoryId = extras.getString("categoryId");
		}

		// Getting a reference to ListView
		listView = (ListView) findViewById(R.id.lv_services);
		doSearch();
	}

	public void doSearch() {
		// show progress bar
		bar = new ProgressDialog(Services.this);
		bar.setIndeterminate(true);
		bar.show();

		String username = preferences.getString(Constants.PREF_USER_NAME, "");
		String password = preferences.getString(Constants.PREF_PASSWORD, "");
		username = "Ten.Arunsawad@yahoo.com";
		password = "123adc123";

		String filter = "<keywords>";
		if (categoryId == null) {
			filter += "<categoryId/>";
		} else {
			filter += "<categoryId>" + categoryId + "</categoryId>";
		}
		filter += "<serviceKeyword>"
				+ ((EditText) findViewById(R.id.services_txtSearch)).getText()
				+ "</serviceKeyword>";
		filter += "<lastPageNumber>" + page + "</lastPageNumber>";
		filter += "</keywords>";
		String msg = String.format(Constants.MSG, "ilertu.services-list",
				username, password,
				preferences.getString(Constants.PREF_LANGUAGE, "en"), filter);

		RequestTask task = new RequestTask();
		task.setListener(this);
		task.execute(Constants.URL_GET_SERVICES, msg);
	}

	@Override
	public void onRequestCompleted(String results) {
		if (results != null) {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder;
			try {
				builder = factory.newDocumentBuilder();
				Document document = builder.parse(new InputSource(
						new StringReader(results)));
				NodeList nodes = document.getElementsByTagName("service");

				// fill in the list items from the XML document
				for (int i = 0; i < nodes.getLength(); i++) {
					Element e = (Element) nodes.item(i);

					int id = Integer.parseInt(e.getAttribute("id"));
					String name = e.getElementsByTagName("name").item(0)
							.getTextContent();
					String desc = e.getElementsByTagName("desc").item(0)
							.getTextContent();
					String imageUrl = e.getElementsByTagName("imageUrl")
							.item(0).getTextContent();
					Service service = new Service(id, name, desc, imageUrl);
					services.add(service);
				}

				// handel more button
				if (nodes.getLength() == Constants.RECORDS_PER_PAGE) {
					if (page == 0) {
						// LoadMore button
						btnLoadMore.setText(getString(R.string.more));
						btnLoadMore.setVisibility(View.VISIBLE);
						// Adding Load More button to lisview at bottom
						listView.addFooterView(btnLoadMore);

						/**
						 * Listening to Load More button click event
						 * */
						btnLoadMore
								.setOnClickListener(new View.OnClickListener() {
									@Override
									public void onClick(View arg0) {
										// Starting a new async task
										page += 1;
										doSearch();
									}
								});
					}
				} else {
					btnLoadMore.setVisibility(View.GONE);
				}

				// get listview current position - used to maintain scroll
				// position
				int currentPosition = listView.getFirstVisiblePosition();

				// create base adapter
				adapter = new ServicesAdapter(Services.this, services);
				listView.setAdapter(adapter);
				listView.setSelectionFromTop(currentPosition, 0);

				// hide progress bar
				bar.hide();

				// star loading image for each service
				for (int i = (page * Constants.RECORDS_PER_PAGE); i < services
						.size(); i++) {
					services.get(i).loadImage(adapter);
				}

				listView.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						TextView txtServiceId = (TextView) view
								.findViewById(R.id.services_txtServiceId);
						Intent intent = new Intent(getApplicationContext(),
								AddService.class);
						intent.putExtra("serviceId", txtServiceId.getText());
						startActivity(intent);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}